var communityService = require('../services/communityService');
var messageUtil = require('../common/utils/messageUtil');
var cacheUtil = require('../common/utils/cacheUtil');
var toolUtil = require('../common/utils/toolUtil');
var fs = require("fs");
var Users = mongoose.model('user');


exports.getCommunityByCommunityId = function (req, res) {
    logger.debug('Trying to get community data');
    var communityId = req.params.communityId;
    var token = req.params.token;
    communityService.getCommunityByCommunityIdService(token, communityId, function (err, results) {
        if (err) {
            logger.error("Failed to get the community data! " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to get the community data! " + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    });
};
exports.backOfficeGetCommunityDetail = function (req, res) {
    var communityId = req.params.communityId;

    communityService.backOfficeGetCommunityDetailService(communityId, function (err, results) {
        if (err) {
            logger.error("Failed to get the backOfficeGetCommunityDetail " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to get the community data! " + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

exports.postCommunityBulletin = function (req, res) {

    var token = req.params.token;
    var input = req.body;

    communityService.postCommunityBulletinService(token, input, function (err, result) {

        if (err) {
            logger.error("Failed to postCommunityBulletinService " + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }

    });
};

exports.postCommunityBulletinServiceByModerator = function (req, res) {

    var token = req.params.token;
    var input = req.body;

    communityService.postCommunityBulletinServiceByModerator(token, input, function (err, result) {

        if (err) {
            logger.error("Failed to postCommunityBulletinService " + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }

    });
};

exports.postCommunityApplication = function (req, res) {
    var token = req.params.token;
    var input = req.body;
    input.user = token;

    communityService.postCommunityApplicationService(input, function (err, result) {
        if (err) {
            logger.error("Failed to postCommunityApplication " + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.searchByCityAndName = function (req, res) {
    logger.debug('Trying to search community by communityName');
    var cityId = req.params.cityId;
    var communityName = req.params.communityName;

    communityService.searchByCityAndNameService(cityId, communityName, function (err, results) {
        if (err) {
            logger.error("Failed to search community by communityName! " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to search community by communityName! " + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    });
};

/**
 * 根据小区ObjID查询所有公告
 */
exports.getCommunityBulletin = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;
    communityService.getCommunityBulletinService(page, token, function (err, results) {
        if (err) {
            logger.error(' Exception happened when get community bulletin...!-' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

exports.getDetailCommunityBulletin = function (req, res) {
    var id = req.params.bulletinId;
    var token = req.params.token;
    var clickSource = req.cparams.clickSource;

    communityService.getDetailCommunityBulletinService(id, function (err, result) {
        if (err) {
            logger.error(' Exception happened when get getDetailCommunityBulletin...!-' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));

            if (clickSource != null) {
                var message = {
                    userId: token,
                    contentId: id,
                    type: 5,
                    clickSource: clickSource,
                    typeDesc: '公告',
                    createTime: new Date().getTime()
                };
                toolUtil.putMessageLogMQ(message);
            }
        }
    })
}


exports.getCommunityTalent = function (req, res) {
    var token = req.params.token;
    communityService.getCommunityTalentService(token, function (err, results) {
        if (err) {
            logger.error(' Exception happened when getCommunityTalent...!-' + err.message);
            res.json(messageUtil.composeFailedMessage(req, ' Exception happened when getCommunityTalent...!-' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
}

exports.getCommunityTalentNew = function (req, res) {
    var token = req.params.token;
    var page = req.prams.page;
    communityService.getCommunityTalentNewService(page, token, function (err, results) {
        if (err) {
            logger.error(' Exception happened when getCommunityTalent...!-' + err.message);
            res.json(messageUtil.composeFailedMessage(req, ' Exception happened when getCommunityTalent...!-' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
}

/**
 * 根据经纬度获取周边小区
 * @param req
 * @param res
 */
exports.getCommunityListByCoordinates = function (req, res) {
    logger.debug('Trying to get the community List by coordinates ...');
    var latitude = req.params.latitude;
    var longitude = req.params.longitude;
    if (latitude != null && longitude != null) {
        communityService.getCommunityListByCoordinates(latitude, longitude, function (err, communities) {
            if (err) {
                logger.error("Failed to get the community List by coordinates ! " + err.message);
                res.json(messageUtil.composeFailedMessage(req, "Failed to get the community List by coordinates ! " + err.message));
            }
            else {
                // 返回消息
                res.json(messageUtil.composeSucceededMessage(req, null, communities.results));
            }
        });
    } else {
        logger.error("Failed to get the community List by coordinates ! - you have to provide the coordinates in the URL...!");
        res.json(messageUtil.composeFailedMessage(req, "Failed to get the community List by coordinates ! - you have to provide the coordinates in the URL...!"));
    }
}

/**
 * 根据关键字获取小区
 */
exports.getCommunityListByKeyword = function (req, res) {
    logger.debug('Trying to get the community List by keyword ...');
    var keyword = req.params.keyword;
    var latitude = req.params.latitude;
    var longitude = req.params.longitude;
    if (keyword != null) {
        communityService.getCommunityListByKeywordService(keyword, latitude, longitude, function (err, communities) {
            if (err) {
                logger.error("Failed to get the community List by keyword ! " + err.message);
                res.json(messageUtil.composeFailedMessage(req, "Failed to get the community List by keyword ! " + err.message));
            }
            else {
                // 返回消息
                res.json(messageUtil.composeSucceededMessage(req, null, communities.results));
            }
        })
    } else {
        logger.error("Failed to get the community List by keyword ! - you have to provide the keyword in the URL...!");
        res.json(messageUtil.composeFailedMessage(req, "Failed to get the community List by keyword ! - you have to provide the keyword in the URL...!"));
    }
};

exports.getCommunityAroundList = function (req, res) {
    var status = req.params.status;
    var token = req.params.token;
    var page = req.params.pageNo;

    communityService.getCommunityAroundListService(page, status, token, function (err, results) {
        if (err) {
            logger.error("Failed to get community around list ! " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to get community around list ! " + err.message));
        }
        else {
            // 返回消息
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

/**
 * 获取商户详情
 */
exports.getCommunityAroundDetails = function (req, res) {
    var id = req.params.id;

    communityService.getCommunityAroundDetailsService(id, function (err, result) {
        if (err) {
            logger.error("Failed to get community around details ! " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to get community around details ! " + err.message));
        }
        else {
            // 返回消息
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

/**
 * 评论商户
 */
exports.postComment = function (req, res) {
    var id = req.params.id;
    var token = req.params.token;
    var input = req.body;

    communityService.postCommentService(id, token, input, function (err, result) {
        if (err) {
            logger.error("Failed to post comment ! " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to post comment ! " + err.message));
        }
        else {
            // 返回消息
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

/**
 * 获取全部小区
 */
exports.getAllCommunity = function (req, res) {
    logger.debug('Trying to get the community List ');
    communityService.getAllCommunityService(function (err, result) {
        if (err) {
            logger.error("Failed to get the community List by keyword ! " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to get the community List by keyword ! " + err.message));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};
exports.getAllCommunityGroups = function (req, res) {
    logger.debug('Trying to get the community groups List ');
    communityService.getAllCommunityGroupsService(function (err, result) {
        if (err) {
            logger.error("Failed to get the community groups List by keyword ! " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to get the community groups List by keyword ! " + err.message));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};
exports.getAllCommunityFromSQL = function (req, res) {
    logger.debug('Trying to get the community groups List ');
    communityService.getAllCommunityFromSQLService(function (err, result) {
        if (err) {
            logger.error("Failed getAllCommunityFromSQL ! " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed getAllCommunityFromSQL!" + err.message));
        }else {
            var len = result.length;
            for(var i = 0; i < len; i++){
                if(result[i].groups == null)
                    continue
                var groupsList = []
                var groupsStr = result[i].groups
                groupsList = groupsStr.replace("[", "").replace("]", "").split(",")
                result[i].groups = groupsList
            }
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};


exports.postCommunitySupplement = function (req, res) {
    var token = req.params.token;
    var input = req.body;

    communityService.postCommunitySupplementService(token, input, function (err, result) {
        if (err) {
            logger.error("Failed to get the postCommunitySupplement! " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to get the postCommunitySupplement! " + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, '内容已提交', null));
        }
    })
};

exports.getCommunitySupplementList = function (req, res) {
    var communityId = req.params.communityId;

    communityService.getCommunitySupplementListService(communityId, function (err, results) {
        if (err) {
            logger.error('Exception happened when getCommunitySupplementList...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when getCommunitySupplementList...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

exports.updateSupplementStatus = function (req, res) {
    var supplementId = req.params.supplementId;
    //logger.debug(req.params);
    communityService.updateSupplementStatusService(supplementId, function (err, result) {

        if (err) {
            logger.error('Exception happened when updateSupplementStatus...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when updateSupplementStatus...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
}

exports.updateCommunity = function (req, res) {
    var communityId = req.params.communityId;
    var input = req.body;
    input.phoneList = JSON.parse(input.phoneList);

    toolUtil.uploadImageService(null, null, req, function (err, images) {
        images.forEach(function (image) {
            if (image != null) {
                input.communityLogo = image;
            }
        });
        communityService.updateCommunityService(communityId, input, function (err, result) {
            if (err) {
                logger.error('Exception happened when updateCommunity...!' + err.message);
                res.json(messageUtil.composeFailedMessage(req, 'Exception happened when updateCommunity...!' + err.message));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, null));
            }
        })
    })
};

exports.getAllCommunityNotice = function (req, res) {
    var communityId = req.params.communityId;

    communityService.getAllCommunityNoticeService(communityId, function (err, results) {
        if (err) {
            logger.error('Exception happened when getAllCommunityNoticeService...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when getAllCommunityNoticeService...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

exports.setNoticeStatus = function (req, res) {
    var input = req.body;

    communityService.setNoticeStatusService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when setNoticeStatus...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when setNoticeStatus...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
}

exports.addNoticeToFresh = function (req, res) {
    var communityId = req.params.communityId;
    var noticeId = req.params.noticeId;

    communityService.addNoticeToFreshService(communityId, noticeId, function (err, result) {
        if (err) {
            logger.error('Exception happened when addNoticeToFresh...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when addNoticeToFresh...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.getCommunityPeopleNumber = function (req, res) {
    var token = req.params.token;

    communityService.getCommunityPeopleNumberService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when getCommunityPeopleNumber...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = {
                number: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
}

exports.getCommunityUser = function (req, res) {
    var token = req.params.token;
    var ts = req.params.ts;

    communityService.getCommunityUserService(token, ts, function (err, result) {
        var data = {
            ts: result.length > 0 ? result[result.length - 1].pinyinSort : ts,
            users: result
        };
        res.json(messageUtil.composeSucceededMessage(req, null, data));
    })
};

exports.deleteNotice = function (req, res) {
    var noticeId = req.params.noticeId;

    communityService.deleteNoticeService(noticeId, function (err, result) {
        if (err) {
            logger.error('Exception happened when deleteNotice...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.deleteNoticeByModerator = function (req, res) {
    var noticeId = req.params.noticeId;
    var communityId = req.params.communityId;

    communityService.deleteNoticeServiceByModerator(noticeId,communityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when deleteNotice...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.getNoticeById = function (req, res) {
    var noticeId = req.params.noticeId;

    communityService.getNoticeByIdService(noticeId, function (err, result) {
        if (err) {
            logger.error('Exception happened when deleteNotice...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.initCommunityAround = function (req, res) {

    communityService.initCommunityAround(function (err, result) {
        if (err) {
            logger.error('Exception happened when initCommunityAround...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.getCommunityGroups = function (req, res) {
    var input = req.body;
    communityService.getCommunityGroups(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when getCommunityGroups ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var result = {list: result[0], totalPage: result[1]};
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    });
};

exports.addCommunityGroup = function (req, res) {

    communityService.addCommunityGroup(req.body,function (err, result) {
        if (err) {
            logger.error('Exception happened when addCommunityGroup...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.updateCommunityGroup = function (req, res) {

    communityService.updateCommunityGroup(req.body,function (err, result) {
        if (err) {
            logger.error('Exception happened when updateCommunityGroup...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.deleteCommunityGroup = function (req, res) {

    communityService.deleteCommunityGroup(req.body,function (err, result) {
        if (err) {
            logger.error('Exception happened when deleteCommunityGroup...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.getCommunityGroupById = function (req, res) {

    communityService.getCommunityGroupById(req.body,function (err, result) {
        if (err) {
            logger.error('Exception happened when getCommunityGroupById...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.getCommunitiesByGroup = function (req, res) {
    var input = req.body;
    communityService.getCommunitiesByGroup(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when getCommuntiesByGroup ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var result = {list: result[0], totalPage: result[1]};
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    });
};

exports.deleteCommunityGroups = function (req, res) {

    communityService.deleteCommunityGroups(req.body,function (err, result) {
        if (err) {
            logger.error('Exception happened when deleteCommunityGroup...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.getIsOpenCommunityByName = function (req, res) {

    communityService.getIsOpenCommunityByName(req.body,function (err, result) {
        if (err) {
            logger.error('Exception happened when deleteCommunityGroup...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.insertCommunityGroups = function (req, res) {

    communityService.insertCommunityGroups(req.body,function (err, result) {
        if (err) {
            logger.error('Exception happened when insertCommunityGroups...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

/*  宝宝树66小区二次改造    add   guo.xiaomin  20170825  start   */
// 生成小区大使信息Excel
exports.exportModeratorManagerInfoData = function (req, res) {
    communityService.exportModeratorManagerInfoData(req, res, function (err, result) {
        if (err) {
            logger.error('Exception happened when exportModeratorManagerInfoData...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    });
};
/*  宝宝树66小区二次改造    add   guo.xiaomin  20170825  end   */

/*  宝宝树66小区二次改造    add   guo.xiaomin  20170912  start   */
// 下载小区大使信息Excel
exports.downLoadModeratorManagerInfoData = function (req, res) {
    communityService.downLoadModeratorManagerInfoData(req, res, function (err, result) {
        if (err) {
            logger.error('Exception happened when downLoadModeratorManagerInfoData...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    });
};
/*  宝宝树66小区二次改造    add   guo.xiaomin  20170912  end   */